<?php

namespace Common;

/**
 * 这里是与项目相关的工具类
 *
 * @author J
 */
class Utils
{

    /**
     * 对密码进行Hash
     */
    public static function getHashPwd($pwd)
    {
        $login_pwd = sha1($pwd . '13911881801');
        return $login_pwd;
    }

    /**
     * 生成银行账号
     */
    public static function getNextAccount($entityType, $operatorId)
    {
        $key = 'account_sn';

        if (S($key) == null) {
            S($key, 1); //计数器设为1
        } else {
            $temp = S($key);
            $temp++;

            if ($temp > 99) {
                $temp = 0;
            }
            S($key, $temp);
        }

        $entity_type = $entityType;
        $day = date('ymd', time());

        $rand = rand(0000, 9999);
        $rand = str_pad($rand, 4, '0', STR_PAD_LEFT);

        return $entity_type . str_pad($operatorId, 3, '0', STR_PAD_LEFT) . $day . $rand . str_pad(S('account_sn'), 2, '0', STR_PAD_LEFT);
    }

    /**
     * 从数据库读出来的钱(分)要用此方法，显示RMB元//移至admin下的common function.php中
     */
    public static function getYuan($dbfen)
    {
      
        //1234 -> 12.34        
        //1 -> 0.01
        //-9 -> -0.09
        $fen = $dbfen;
        if ($dbfen < 0) {
            $fen = -1 * $dbfen;
        }
        $fenstr = $fen;

        if (strlen($fen) < 3) {
            $fenstr = str_pad($fen, 3, '0', STR_PAD_LEFT);
        }
        $length = strlen($fenstr);

        $result = substr($fenstr, 0, $length - 2) . '.' . substr($fenstr, $length - 2, 2);
        if ($dbfen < 0) {
            return "-" . $result;
        }
        return $result;
    }

    public static function getYuanEdit($dbfen)
    {
        $r = getYuan($dbfen);
        $length = strlen($r);
        $result = substr($r, 0, $length - 3);
        return $result;
    }

    /**
     * 存入数据库的钱(元)要用此方法，存成RMB分
     */
    public static function getFen($yuan)
    {
        return $yuan * 100; //intval()函数会出错
    }

    /**
     * 交易记录序列号
     */
    public static function getSn()
    {
        return time() . rand(1000, 9999);
    }

    /**
     * 提现、合同、充值、记录交易号
     */
    public static function getAccount($id)
    {
        $real_num = str_pad($id, 8, '0', STR_PAD_LEFT);
        return $real_num;
    }

    /**
     * 分页一张表
     */
    public static function pages($table, $where, $pageset, $order)
    {
        $tableInfo = M($table);
        $record_sum = $tableInfo->where($where)->count(); //记录总数
        $page = new \Common\Common\Page($record_sum, $pageset);
        $sql = "select * from top_" . $table . " where " . $where . " order by " . $order . $page->limit;
        $info = $tableInfo->query($sql);
        $show = $page->fpage();
        return array(
            'info' => $info,
            'page' => $show,
        );
    }
    /**
     * 分页左链接查询
     */
    public static function left_join_pages($table,$jointable,$filed,$dl_on, $where, $pageset, $order)
    {
        $tableInfo = M($table);
        $record_sum = $tableInfo->where($where)->count(); //记录总数
        $page = new \Common\Common\Page($record_sum, $pageset);
        $sql = "select ".$filed." from top_" . $table ." LEFT JOIN top_".$jointable." ON ".$dl_on. " WHERE " . $where . " order by " . $order . $page->limit;
        $info = $tableInfo->query($sql);
        $show = $page->fpage();
        return array(
            'info' => $info,
            'page' => $show,
        );
    }

    /**
     * 分页多张张表
     */
    public static function tablesPage($table, $jiontable, $filed, $where, $pageset, $gorup, $order)
    {
        $tableInfo = M($table);
        if ($gorup) {
            $sql = "SELECT " . $filed . " FROM top_" . $table . " as a," . $jiontable . " where " . $where . " group by " . $gorup;
            $record_sum = count($tableInfo->query($sql));
            $page = new \Common\Common\Page($record_sum, $pageset);
            $sql = "SELECT " . $filed . " FROM top_" . $table . " as a," . $jiontable . " where " . $where . " group by " . $gorup . $page->limit;
        } else {
            $sql = "SELECT " . $filed . " FROM top_" . $table . " as a," . $jiontable . " where " . $where;
            $record_sum = count($tableInfo->query($sql));
            $page = new \Common\Common\Page($record_sum, $pageset);
            $sql = "SELECT " . $filed . " FROM top_" . $table . " as a," . $jiontable . " where " . $where . $page->limit;
        }

        $info = $tableInfo->query($sql);
        $show = $page->fpage();
        return array(
            'info' => $info,
            'page' => $show,
        );
    }

    /**
     * 处理图片地址
     */
    public static function GetRealImageUrl($url)
    {
        $string = str_replace("#file1#", C('FILE1_BASE_URL'), $url);
        return $string;
    }

    public static function GetImageUrl($url, $width, $height, $fix)
    {
        //http://www.abc.com/folder/a/b/c.jpg

        $u = str_replace("http://", "", $url);
        $index = strpos($u, "/");

        $host = substr($u, 0, $index);
        $len = strlen($u);
        $other = substr($u, $index, $len - $index);

        $fixStr = "";
        if ($fix) {
            $fixStr = "/c";
        }
        $http = "http://";
        $ret = $http . $host . $fixStr . strval("/") . strval($width) . strval("/") . strval($height) . $other;
        return $ret;
    }

    public static function DispCommissionRate($dbVal)
    {
        return $dbVal / 1000 . "‰";
    }

    public static function GetCommissionRate($dbVal)
    {
        return $dbVal / 1000;
    }
    //计算订单利息
    public static function CalcCommission($dbRate, $amount)
    {
        return round($dbRate * $amount / 1000000);
    }

    public static function SetCommission($val)
    {
        return $val * 1000;
    }

    public static function setTax($val)
    {
        return round(($val * 1 * 100) / 100);
    }

    public static function oldSetTax($val)
    {
        return ($val * 4 * 100) / 1000;
    }

    public static function setServiceFeeTax($val, $id, $detail)
    {
        $feeRateInfo = M('operator_invoice_fee')->where("operator_id = '{$id}' && detail = '{$detail}'")->find();
        $feeRate = $feeRateInfo['fee_rate'] / 10000;
        return round(($val * $feeRate * 100) / 100);
    }
    //获取当前登陆用户的冻结资金
    public static function getFrozenFen($entityType, $entityId)
    {
        $where['entity_type'] = $entityType;
        $where['entity_id'] = $entityId;
        //申请属于待审核状态的
        $applyStateWait = Top::ApplyStateWait;
        //审核通过，待财务处理
        $applyStatePass = Top::ApplyStatePass;
        
        $withdrawList = M('account_withdraw')->where($where)->where("state = '{$applyStateWait}' or state = '{$applyStatePass}'")->field('id,amount,state')->select();
        $serviceList = M('service_charge')->where($where)->where("state = 0")->field('id,service_money,state')->select();
        $sum = 0;
        foreach ($withdrawList as $key => $vo) {
            $sum += $vo['amount'];
        }
        $service_sum = 0;
        foreach ($serviceList as $k =>$v){
            $service_sum +=$v['service_money'];
        }
        $total_sum = $sum + $service_sum;

        return $total_sum;
    }

    public static function getProviderAllFrozenFen($entityType, $entityId)
    {
        $where['entity_type'] = $entityType;
        $where['entity_id'] = $entityId;
        $applyStateWait = Top::ApplyStateWait;
        $applyStatePass = Top::ApplyStatePass;

        $withdrawList = M('account_withdraw')->where($where)->where("state = '{$applyStateWait}' or state = '{$applyStatePass}'")->field('id,amount,state')->select();
        $sum = 0;
        foreach ($withdrawList as $key => $vo) {
            $sum += $vo['amount'];
        }

        $tourOrderList = M('order_tour')->where("provider_id = '{$entityId}' && (state = 9 || state = 10 || state = 12)")->select();
        foreach ($tourOrderList as $k => $v) {
            if ($v['fullpay_time'] != '') {
                $sum += $v['price_total'] + $v['price_adjust'] - Utils::CalcCommission($v['commission_rate'], $v['price_total'] + $v['price_adjust']);
            } else {
                $sum += $v['prepay_amount'] - Utils::CalcCommission($v['commission_rate'], $v['prepay_amount']);
            }
        }

        return $sum;
    }


    public static function getProviderInOperatorFrozenFen($entityType, $entityId, $operatorId)
    {
        $where['entity_type'] = $entityType;
        $where['entity_id'] = $entityId;
        $where['operator_id'] = $operatorId;
        $applyStateWait = Top::ApplyStateWait;
        $applyStatePass = Top::ApplyStatePass;

        $withdrawList = M('account_withdraw')->where($where)->where("state = '{$applyStateWait}' or state = '{$applyStatePass}'")->field('id,amount,state')->select();
        $sum = 0;
        foreach ($withdrawList as $key => $vo) {
            $sum += $vo['amount'];
        }

        $tourOrderList = M('order_tour')->where("provider_id = '{$entityId}' && provider_operator_id = '{$operatorId}' && (state = 9 || state = 10 || state = 12)")->select();

        foreach ($tourOrderList as $k => $v) {
            if ($v['fullpay_time'] != '') {
                $sum += $v['price_total'] + $v['price_adjust'] - Utils::CalcCommission($v['commission_rate'], $v['price_total'] + $v['price_adjust']);
            } else {
                $sum += $v['prepay_amount'] - Utils::CalcCommission($v['commission_rate'], $v['prepay_amount']);
            }
        }

        return $sum;
    }

    public static function getProviderFrozenFen($entityType, $entityId, $operatorId)
    {
        $where['entity_type'] = $entityType;
        $where['entity_id'] = $entityId;
        $where['operator_id'] = $operatorId;
        $applyStateWait = Top::ApplyStateWait;
        $applyStatePass = Top::ApplyStatePass;

        $withdrawList = M('account_withdraw')->where($where)->where("state = '{$applyStateWait}' or state = '{$applyStatePass}'")->field('id,amount,state')->select();
        $sum = 0;
        foreach ($withdrawList as $key => $vo) {
            $sum += $vo['amount'];
        }

        return $sum;
    }

    public static function getAvailableFen($balanceFen, $forzenFen)
    {
        return $balanceFen - $forzenFen;
    }

    public static function getAgencyAvailableFen($entityId)
    {
        $frozenFen = Utils::getFrozenFen(Top::EntityTypeAgency, $entityId);
        $agency = M('agency')->where("id=" . $entityId)->find();

        $balance = $agency['account_balance'] - $frozenFen;
        return $balance;
    }


    public static function getProviderAvailableFen($entityId)
    {
        $frozenFen = Utils::getFrozenFen(Top::EntityTypeProvider, $entityId);
        $agency = M('provider')->where("id=" . $entityId)->find();

        $balance = $agency['account_balance'] - $frozenFen;
        return $balance;
    }

    public static function getBatch()
    {
        return time() . rand(1000, 9999);
    }


    public static function setFlightTax($val)
    {
        return (int)round($val * (1 - (4 / 1000)));
    }

    public static function trimall($str)
    {
        $qian = array(" ", "　", "\t", "\n", "\r");
        $hou = array("", "", "", "", "");
        return str_replace($qian, $hou, $str);
    }

    /**
     * CURL 仿POST
     */
    public static function vpost($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_TIMEOUT,  30);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public static function setEncrypt($id)
    {
        $rep = new STD3Des ();
        return $rep->encrypt($id);
    }


    public static function getDecrypt($id)
    {
        $rep = new STD3Des ();
        return $rep->decrypt($id);
    }

    public static function getOperatorName($id)
    {
        if ($id == 1) {
            $name = '北京运营中心';
        } else if ($id == 2) {
            $name = '测试运营中心';
        } else if ($id == 3) {
            $name = '天津运营中心';
        } else if ($id == 4) {
            $name = '河北运营中心';
        } else if ($id == 5) {
            $name = '唐山运营中心';
        } else if ($id == 6) {
            $name = '安徽运营中心';
        }
        return $name;
    }

    /**
     * 充值申请通知
     */
    public static function topUpTemplateId()
    {
        $templateId = "UCwVCO22m0otjFd0-j6ro_V9OgmmaLstVg07N7q0o2c";
        return $templateId;
    }

    /**
     * 提现申请通知
     */
    public static function withDrawTemplateId()
    {
        $templateId = "tgQ20abp_xnt_zOd3ORY34mUWMWrRJhA2A0TlVWkY58";
        return $templateId;
    }

    /**
     * 机票订单支付成功通知
     */
    public static function flightPaySuccessTemplateId()
    {
        $templateId = "8iOAJaax9PyidEKyphHKzQfoC5XDGbXxatxnli1pJk4";
        return $templateId;
    }

    /**
     * 机票出票成功通知
     */
    public static function flightDrawSuccessTemplateId()
    {
        $templateId = "xs7GOnv51V2ahfBGZm7TzkmErhCYZ8Ke5nMCKY-PUg0";
        return $templateId;
    }


    /**
     * 机票退款通知
     */
    public static function flightOrderRefundTemplateId()
    {
        $templateId = "cCmfjkLn24vK4cdIwDb1HxUkP_C1dL5iap6ioy8L44w";
        return $templateId;
    }

    /**
     * 订单创建成功通知
     */
    public static function orderCreateSuccessTemplateId()
    {
        $templateId = "JBR7Ad_6KRhmGTMaMsN-AtMCn5XuvcM3AOIQIlNpkV8";
        return $templateId;
    }


    /**
     * 订单状态变更通知
     */
    public static function orderStateChangeTemplateId()
    {
        $templateId = "gUkYu23ONVLaEFY-ZyzideM9432cI3FhzOL6HkZfbbA";
        return $templateId;
    }


    /**
     * 订单付款成功通知
     */
    public static function orderPaySuccessTemplateId()
    {
        $templateId = "cbUBQxWXSja_SyjqnJ0z1NAVWwjXwUktKaOAYsYITyA";
        return $templateId;
    }


    /**
     * 产品审核结果通知
     */
    public static function productCheckResultTemplateId()
    {
        $templateId = "-CHkJDIExvoV55r6tNiG5GMjGo--NrhfUCZv6fzPEe4";
        return $templateId;
    }


    /**
     * 产品团期提醒
     */
    public static function productSkuRemindTemplateId()
    {
        $templateId = "Sk_3-V25enQ9BeAojodRsvJMe_mhEOlNvLtg0Jmx8SU";
        return $templateId;
    }


}
